<template>
  <uv-popup ref="canvasPosterPopup" :safeAreaInsetBottom="false" :closeOnClickOverlay="false" bgColor="none" overlayOpacity="0.7" zIndex="999" @touchmove.stop.prevent="">
    <view :class="[`${prefixCls}-canvas-poster-container`]" :style="{ marginBottom: shareMode == 'compose' ? '284rpx' : false }">
      <!-- close -->
      <view class="popup-close" @click="onClosePoster"><uv-icon name="close" color="#333" size="20" /></view>

      <!-- loading -->
      <view v-if="!posterPath" class="poster-empty" :style="{ height: `${posterHeight}px`, width: `${posterWidth}px` }">
        <uv-loading-icon text="海报加载中..." :color="theme" :textStyle="{ marginTop: '10px' }" vertical textSize="30rpx" :textColor="theme" />
      </view>

      <!-- poster -->
      <uv-image v-else class="poster-image" radius="8px" mode="scaleToFill" :src="posterPath" :width="posterWidth" :height="posterHeight" />

      <!-- button -->
      <!-- 海报操作单一模式 -->
      <view class="poster-button" v-if="shareMode === 'single'">
        <uv-button class="save-btn" :customStyle="customStyle" :color="buttonColor || theme" size="small" shape="circle" :disabled="!posterPath" @click="onSavePoster">
          {{ ['wechatOfficialAccount', 'H5'].includes($Platform.name) ? '长按图片保存' : '保存图片' }}
        </uv-button>
      </view>
    </view>

    <!-- 海报操作组合模式 -->
    <cu-footer-operate v-if="shareMode === 'compose'">
      <uv-text align="center" size="24rpx" :customStyle="{ marginBottom: '20rpx' }" text="分享当前页面到"></uv-text>
      <view class="operate-share">
        <uv-button
          icon="weixin-fill"
          iconSize="24px"
          iconColor="#fff"
          text="微信好友"
          open-type="share"
          @click="onShareForward('WXSceneSession')"
          v-if="canShareForward('forward')"
        />
        <!-- #ifdef APP-PLUS || H5 -->
        <uv-button icon="moments" iconSize="24px" iconColor="#fff" text="朋友圈" open-type="share" @click="onShareForward('WXSceneTimeline')" v-if="canShareForward('forward')" />
        <!-- #endif -->
        <!-- #ifdef H5 -->
        <uv-button icon="attach" iconSize="24px" iconColor="#fff" text="复制链接" @click="onShareCopyLink" v-if="canShareForward('link')" />
        <!-- #endif -->
        <uv-button icon="download" iconSize="24px" text="保存图片" @click="onSavePoster" v-if="canShareForward('image')" />
      </view>
      <uv-text align="center" :customStyle="{ marginTop: '20rpx' }" text="取消" @click="onClosePoster"></uv-text>
    </cu-footer-operate>

    <!-- 绘制海报 -->
    <Poster ref="posterTemp" @onSuccess="getPoster" />
  </uv-popup>
</template>

<script>
import { mapGetters } from 'vuex'
import Poster from './components/index'
import PosterConfig from './components/poster'
import $store from '@/store'
export default {
  name: 'cuPoster',
  components: { Poster },
  mixins: [],
  props: {
    posterImage: {
      type: String,
      default: '',
    },
    posterJson: {
      type: Object,
      default: () => ({}),
    },
    buttonColor: {
      type: String,
      default: '',
    },
    customStyle: {
      type: Object,
      default: () => ({}),
    },
    shareInfo: {
      type: Object,
      default: () => ({}),
    },
    shareMethods: {
      type: Array,
      default: () => $store.getters.platform.share.methods,
    },
    // 分享操作模式
    shareMode: {
      type: String,
      // #ifdef APP-PLUS
      default: 'compose', // single: 单一模式；'compose'：组合按钮模式
      // #endif
      // #ifndef APP-PLUS
      default: 'single', // single: 单一模式；'compose'：组合按钮模式
      // #endif
    },
  },
  data() {
    return {
      posterPath: '',
    }
  },
  // 侦听属性
  watch: {},
  // 计算属性
  computed: {
    ...mapGetters(['theme', 'platform']),

    posterWidth() {
      return this.posterJson?.css?.width || this.$Platform.device.windowWidth * 0.85
    },
    posterHeight() {
      return this.posterJson?.css?.height || 500
    },
    buttomSafeArea() {
      return this.$Platform.device.safeAreaInsets.bottom || 10
    },

    canShareForward(method) {
      return (method) => {
        return this.platform.share.methods.includes(method) && this.shareMethods.includes(method)
      }
    },
  },

  created() {},
  mounted() {},
  destroyed() {},
  options: {
    styleIsolation: 'shared',
  },
  methods: {
    // 绘制海报
    async drawPoster() {
      this.posterPath = ''
      let poster = this.posterJson

      // 若 posterJson为空，使用默认海报示例
      if (!Object.keys(poster).length) {
        poster = PosterConfig()
      }
      // console.log('🚀 ~ drawPoster ~ poster:', poster)
      await this.$refs.posterTemp.setPosterTemp(poster)
    },

    // 获取海报信息
    getPoster(e) {
      this.posterPath = e
    },

    // 保存海报
    onSavePoster() {
      if (['WechatOfficialAccount', 'H5'].includes(this.$Platform.name)) {
        this.$uv.toast('请长按图片保存')
        return
      }

      this.$Helper.saveImageToAlbum(this.posterPath)
    },

    // 打开海报分享弹窗开始绘图
    onOpenPoster() {
      // 隐藏菜单栏
      // 若启用pages.js中配置底部菜单则释放此处注释
      // this.$nextTick(() => {
      //    const { path } = this.$Route
      //    if (TABBAR.includes(path)) uni.hideTabBar()
      // })
      this.posterPath = this.posterImage
      this.$refs.canvasPosterPopup.open()
      // 如果有传入的海报则以传入的为优先展示，不执行前端绘制海报图
      if (uni.$uv.test.image(this.posterImage)) return

      // popup打开，绘图组件载入后 在进行绘图操作
      // #ifdef APP-PLUS
      setTimeout(() => {
        this.drawPoster() // APP端绘图组件未完整载入，用延时方式处理
      })
      // #endif

      // #ifndef APP-PLUS
      this.$nextTick(() => {
        this.drawPoster()
      })
      // #endif
    },

    onShareForward(scene) {
      this.$Platform.share.shareForwardWechat({ vm: this, scene })
    },

    onShareCopyLink() {
      this.$Helper.copyText(this.shareInfo.link)
    },

    // 取消
    onClosePoster() {
      this.$refs.canvasPosterPopup.close()
      // 若启用pages.js中配置底部菜单则释放此处注释
      // const { path } = this.$Route
      // this.$nextTick(() => {
      //    if (TABBAR.includes(path)) uni.showTabBar()
      // })
      this.$emit('onClosePoster')
    },
  },
}
</script>

<style lang="scss" scoped>
.#{prefixCls('canvas-poster-container')} {
  position: relative;
  min-width: 500rpx;
  min-height: 400rpx;
  text-align: center;
  .poster-empty {
    @include flex(column);
    width: 500rpx;
    height: 600rpx;
    justify-content: center;
    align-items: center;
    text-align: center;
    color: $uv-info;
  }
  .poster-image {
    overflow: hidden;
  }
  .poster-button {
    margin-top: 20rpx;
    @include flex;
    justify-content: center;
    ::v-deep .uv-button-wrapper,
    .save-btn {
      width: 240rpx;
    }
  }
  .popup-close {
    position: absolute;
    width: 40rpx;
    height: 40rpx;
    top: 30rpx;
    right: 30rpx;
    z-index: 99;
  }
}

::v-deep .#{prefixCls('footer-operations')} {
  border-radius: 20rpx 20rpx 0 0;
}
.operate-share {
  display: flex;
  align-items: center;
  justify-content: space-around;
  overflow: auto;
  ::v-deep {
    .uv-button-wrapper:nth-child(1) .uv-button .uv-icon {
      background-color: #0fd161;
    }
    .uv-button-wrapper:nth-child(2) .uv-button .uv-icon {
      background-color: #00d19d;
    }
    .uv-button-wrapper:nth-child(3) .uv-button .uv-icon {
      background-color: $uv-primary;
    }
    .uv-button-wrapper:nth-child(4) .uv-button .uv-icon {
      background-color: #ddd;
    }
    .uv-button {
      height: auto;
      @include flex(column);
      border: none !important;
      padding: 10rpx 20rpx;
      .uv-icon {
        padding: 10rpx;
        border-radius: 50%;
        .uv-icon__icon {
          margin-right: 0 !important;
        }
      }
      .uv-button__text {
        margin-top: 20rpx;
        font-size: 24rpx !important;
      }
    }
  }
}
</style>
